package gamecontrollerserver;

import ControllerSerialization.ControllerSerializer;
import EventProcessor.EventProcessor;
import EventProcessor.MouseEventProcessor;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.simpleframework.http.core.Container;
import org.simpleframework.http.Response;
import org.simpleframework.http.Request;
import java.io.PrintStream;

/**
 *
 * @author luc0
 */
public class SimpleHTTPHandler implements Container {

    private EventProcessor eventProcessor = EventProcessor.getInstance();
    private MouseEventProcessor mouseEventProcessor = new MouseEventProcessor();
    public void handle(Request request, Response response) {

        PrintStream body;

        try {
            body = response.getPrintStream();
            //System.out.println("----> IP:"+ request.getClientAddress().getHostName());
           // long time = System.currentTimeMillis();
            if(request.contains("mouseJoystick")){
                String x = request.getValue("x");
                String y = request.getValue("y");
                String begin = request.getValue("mouseJoystick");
                if(begin.equals("begin")){
                    mouseEventProcessor.moveMouse(Integer.valueOf(x),Integer.valueOf(y), 1);
                }else {
                    mouseEventProcessor.endMouse();
                }
                
            }else if (request.contains("JoystickPressed")) {
                String joystickId = request.getValue("JoystickPressed");
                eventProcessor.joystickPressed(joystickId);
            } else if (request.contains("JoystickReleased")) {
                String joystickId = request.getValue("JoystickReleased");
                eventProcessor.joystickReleased(joystickId);

            } else if (request.contains("KeyPressed")) {
                String buttonId = request.getValue("KeyPressed");
                eventProcessor.pressButton(buttonId);
            } else if (request.contains("KeyReleased")) {
                String buttonId = request.getValue("KeyReleased");
                eventProcessor.releaseButton(buttonId);
            } else if (request.contains("isServerOnline")) {
                body.println("Server is on :)");
            } else  if (request.contains("requestController")) {
                ControllerSerializer serializer = ControllerSerializer.getInstance();
                body.println(serializer.getControllerAsString());
            } else if (request.contains("iphoneIsAlive")) {
               body.println("serverIsAlive");
           
            }
           

            body.close();
        } catch (IOException ex) {
            Logger.getLogger(SimpleHTTPHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
